-- 引入redis
local Redis = require('resty.redis')
-- 定义释放redis连接的方法
local function close_redis(red)  
    if not red then  
        return  nil;
    end  
    local ok, err = red:close()  
    if not ok then  
        ngx.say("close redis error : ", err)  
    end  
end   
--创建实例  
local red = Redis:new()  
--设置超时（毫秒）  
red:set_timeout(1000)  

function set(ip, port, key, value)
    -- 建立连接
    local ok, err = red:connect(ip, port)  
    if not ok then  
        ngx.say("connect to redis error : ", err)  
        return close_redis(red)  
    end 

    -- 写数据
    ok, err = red:set(key, value)
    if not ok then  
        ngx.say("set msg error : ", err)  
        return close_redis(red)  
    end  
end
function get(ip, port, key)
    -- 建立连接
    local ok, err = red:connect(ip, port)  
    if not ok then  
        ngx.say("connect to redis error : ", err)  
        return close_redis(red)  
    end 

    -- 读数据
    local resp, err = red:get(key)
    if not resp then  
        ngx.say("get msg error : ", err)  
        return close_redis(red)  
    end  
    return resp;
end

--建立连接 ,这里要指定redis的安装的ip和端口
local ip = "127.0.0.1"  
local port = 6379  

set(ip, port, "key", ngx.var[1])

local val = get(ip, port, "key")

ngx.say("val: "..val)
